package org.dk.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("eSGoodsController")
public class ESGoodsController {

    @Autowired
    public RestHighLevelClient restHighLevelClient;

    @RequestMapping("searchDoc")
    public String searchDoc(String title, Model model, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) throws IOException {

        // 1.创建查询请求对象
        SearchRequest dongdongshop = new SearchRequest("dongdongshop");
        /*boolean exists = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
       */
        // 2.构建搜索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // (1)查询条件 使用QueryBuilders工具类创建
        // 精确查询
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("title", title);

        /*BoolQueryBuilder bool = new BoolQueryBuilder();
        if(title != null && !"".equals(title)){
            bool.must(QueryBuilders.matchQuery("goods_name",title));
            searchSourceBuilder.query(bool);
        }else {
            searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        }*/
        //高亮显示
        HighlightBuilder highlight = new HighlightBuilder();
        //指定高亮的字段,需要和查询的字段一致
        highlight.field("title");
        //设置标签
        highlight.preTags("<font color='red'>");
        highlight.postTags("</font>");
        //根据字段查询
        searchSourceBuilder.highlighter(highlight);
        searchSourceBuilder.from((pageNum - 1) * pageSize);
        searchSourceBuilder.size(pageSize);
        SearchResponse search = null;
        searchSourceBuilder.query(matchQueryBuilder);
        dongdongshop.source(searchSourceBuilder);
        search = restHighLevelClient.search(dongdongshop, RequestOptions.DEFAULT);
        // 4.客户端查询请求
        /*try {
            search = restHighLevelClient.search(dongdongshop, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        //获取查询到的数据中的hits
        //固定代码
        SearchHits hits = search.getHits();
        //SearchHit[] hitsArr = hits.getHits();
        System.out.println(JSON.toJSONString(hits));
        // 5.查看返回结果
        List<Map> list = new ArrayList<>();
        for (SearchHit documentFields : hits.getHits()) {
            Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
            Map<String, HighlightField> highlightFields = documentFields.getHighlightFields();//获取高亮字段
            HighlightField name = highlightFields.get("title");
            //替换
            if (name != null){
                Text[] fragments = name.getFragments();
                StringBuilder stringBuilder = new StringBuilder();
                for (Text fragment : fragments) {
                    stringBuilder.append(fragment);
                }
                sourceAsMap.put("title",stringBuilder.toString());
            }
            list.add(sourceAsMap);
            System.out.println(sourceAsMap);
        }
        model.addAttribute("goodsList",list);
        model.addAttribute("search",title);
        model.addAttribute("pageNum",pageNum);
        model.addAttribute("pageSize",pageSize);
        System.out.println(JSONObject.toJSONString(list));
        return "search";
    }
}
